package com.domainchen.framework.core.holder;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.domainchen.framework.core.util.Reflections;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月11日 上午12:05:12
 * @类说明 Bean 助手类
 */
public final class BeanHolder {

	private static Logger logger = LoggerFactory.getLogger(BeanHolder.class);

	/**
	 * 定义Bean映射(用于存放 Bean 类与Bean实例的映射关系)
	 */
	private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();

	static {
		Set<Class<?>> beanClassSet = ClassHolder.getBeanClassSet();
		System.out.println("==============================================================================");
		for (Class<?> beanClass : beanClassSet) {
			Object obj = Reflections.newInstance(beanClass);
			System.out.println("[Bean管理]:"+beanClass.getName()+"\t"+obj.toString());
			BEAN_MAP.put(beanClass, obj);
		}
	}

	/**
	 * 获取Bean 映射
	 * 
	 * @return
	 */
	public static Map<Class<?>, Object> getBeanMap() {
		return BEAN_MAP;
	}

	/**
	 * 获取Bean 实例
	 * 
	 * @param cls
	 * @return
	 */
	public static <T> T getBean(Class<?> cls) {
		if (!BEAN_MAP.containsKey(cls)) {
			throw new RuntimeException(" can not get  bean by class:" + cls);
		}
		return (T) BEAN_MAP.get(cls);
	}

	/**
	 * 设置Bean 实例
	 * @param cls
	 * @param obj
	 */
	public static void setBean(Class<?> cls, Object obj) {
		BEAN_MAP.put(cls, obj);
	}
}
